﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using DAL;

namespace StudentManagerPro.Student
{
    public partial class AddStudent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //首次加载：初始化班级下拉框
                this.ddlClass.DataSource = new StudentClassService().GetStudentClass();//设置数据源
                this.ddlClass.DataTextField = "ClassName";//设置下拉框显示文本
                this.ddlClass.DataValueField = "ClassId";//设置显示文本对应的值（该值是隐藏的）
                this.ddlClass.DataBind();//调用数据绑定方法
            }
            this.ltaMsg.Text = "";
        }

        /// <summary>
        /// 提交到数据库：添加学员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddStudent_Click(object sender, EventArgs e)
        {
            //1.验证验证码是否正确
            if (Session["CheckCode"].ToString() != this.txtValidateCode.Text)
            {
                this.ltaMsg.Text = "<script type='text/javascript'>alert('验证码不正确！')</script>";
                return;
            }
            //2.判断身份证号是否存在
            StudentService studentService = new StudentService();
            if (studentService.IsExistsStudentIdNo(this.txtStuIdNo.Text))
            {
                this.ltaMsg.Text = "<script type='text/javascript'>alert('该学员已存在！')</script>";
                return;
            }
            //3.封装对象
            Students student = new Students
            {
                StudentName = this.txtStuName.Text,
                Gender = this.ddlGender.Text,
                Birthday = Convert.ToDateTime(this.txtStuBirthday.Text),
                ClassId = Convert.ToInt32(this.ddlClass.SelectedValue),
                PhoneNumber = this.txtPhoneNumber.Text,
                StudentAddress = this.txtStuAddress.Text,
                StudentIdNo = this.txtStuIdNo.Text,
            };
            //4.调用后台
            try
            {
                var newStudentId = studentService.AddStudent(student);//返回新增的学号
                if (newStudentId > 0)
                {
                    Response.Redirect("~/Student/UpLoadImage.aspx?IsModify=1&id=" + newStudentId, false);//添加成功跳转到上传图片页面
                }
            }
            catch (Exception ex)
            {
                this.ltaMsg.Text = "<script type='text/javascript'>alert('更新学员信息失败："+ex.Message+"')</script>";
            }

        }
    }
}